package com.woniuxy.qiantai.config;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class SendSmsUtils {

    /**
     * 发送短信验证码
     */
    public static void sendCode(String phoneNumber,RedisTemplate<String,String> stringRedisTemplate){

        int appid = 1400638316;
        String appkey = "6b4966a7346897791a68cef2d0bc4f73";
        int templateId = 1319715; //模板ID
        String smsSign = "ITchats";
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        try{
            String[] params = {String.valueOf(code), "5"}; //短信中的参数
            SmsSingleSender ssender = new SmsSingleSender(appid,appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86",phoneNumber,templateId,
                    params,smsSign,"","");
            System.out.println("-----------------");
            System.out.println(code);
            System.out.println(phoneNumber);
            System.out.println("-----------------");
            stringRedisTemplate.opsForValue().set(phoneNumber, String.valueOf(code),5, TimeUnit.MINUTES);
            System.out.println(result);
        }catch (HTTPException e){
            e.printStackTrace();
        }catch (JSONException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 发送短信
     * @param phoneNumber
     * @param password
     * @param templateId
     */
    public static void sendAccount(String phoneNumber,String password,Integer templateId){
        int appid = 1400638316;
        String appkey = "6b4966a7346897791a68cef2d0bc4f73";
        String smsSign = "ITchats";
        try{
            String[] params = {phoneNumber, password}; //短信中的参数
            SmsSingleSender ssender = new SmsSingleSender(appid,appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86",phoneNumber,templateId,
                    params,smsSign,"","");
        }catch (HTTPException e){
            e.printStackTrace();
        }catch (JSONException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}